<template>
  <a-card>
    <a-spin :spinning="spinning" size="large">
      <a-form-model ref="rulesForm" :model="form" :rules="rules" :labelCol="{ lg: { span: 2 }, sm: { span: 4 } }" :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }">
        <a-form-model-item label="商品">
          <div>
            <a-button type="primary" @click="visible = true">添加商品</a-button>
            <a-button style="margin-left: 8px" :disabled="createImgFlag" @click="handleCreateImg">生成搭配图</a-button>
          </div>
          <!--          Jrecord.id+record.colorno-->
          <a-table
            style="margin-top: 20px"
            :rowKey="record => JSON.stringify(record)"
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
            :columns="columns"
            :data-source="productList"
            :pagination="false"
          >
            <span class="product-wrapper" slot="product" slot-scope="item">
              <img slot="cover" class="img" :src="item.imgurl" :alt="item.value" v-if="item.imgurl" />
              <img slot="cover" class="img" :alt="item.value" src="https://img.bzhz.jnbygroup.com/cloth.png" v-else />
              <div class="text">
                <div class="t">{{ item.value }}</div>
                <div class="t">{{ item.name }}</div>
                <div class="t">{{ item.color_name }}/{{ item.color_name }}</div>
              </div>
            </span>
            <span slot="action" slot-scope="text, record, index">
              <a-icon type="delete" @click="handleDeleteProduct(index)" />
            </span>
          </a-table>
        </a-form-model-item>
        <a-form-model-item label="效果图" prop="imgList">
          <JImageUpload :uploadParams="getUploadParams()" :isMultiple="true" :fileSize="10" :number="9" :accept="'image/*'" @fileChange="fileImageChange" v-model="imgList"></JImageUpload>
          <div class="upload__tip" style="line-height: 16px">图片小于10mb，格式jpg、png，最多9张。建议像素670X720。</div>
        </a-form-model-item>
        <a-form-model-item label="效果视频" prop="videoList">
          <JImageUpload :uploadParams="getUploadParams()" :isMultiple="true" :fileSize="300" :number="9" :accept="'video/*'" @fileChange="fileVideoChange" v-model="videoList"></JImageUpload>
          <div class="upload__tip" style="line-height: 16px">视频小于300mb</div>
        </a-form-model-item>
        <template v-for="tag in tags">
          <a-form-model-item style="margin-bottom: 0" :label="tag.title">
            <template v-for="t in tag.children">
              <a-checkable-tag :key="t.code" :checked="form.labelList.indexOf(t.code) > -1" @change="checked => handleTagChange(t.code, checked)">
                {{ t.title }}
              </a-checkable-tag>
            </template>
          </a-form-model-item>
        </template>
        <a-divider />

        <a-form-model-item :wrapperCol="{ span: 24 }" style="text-align: center">
          <a-button type="primary" @click="handleSubmit">保存</a-button>
          <a-button style="margin-left: 8px" @click="handleBack">取消</a-button>
        </a-form-model-item>
      </a-form-model>
    </a-spin>
    <a-drawer title="商品库" :width="840" :zIndex="4" @close="visible = false" :visible="visible" :destroyOnClose="true">
      <Product :isEmit="true" @add="handleAddProduct" :gender="-1" :allowGetTag="false" :allowGetPrice="false"></Product>
    </a-drawer>
    <konva-img :konvaImgVisible.sync="konvaImgVisible" :createStylingList="createStylingList"></konva-img>
  </a-card>
</template>
<script>
import globalData from '@/assets/js/common'
import JImageUpload from '@/components/qiniuUpload/JImageUpload.vue'
import Product from '@views/box/workbench/fashioner/module/product'
import KonvaImg from './components/KonvaImg'
import { addCondition, matchCreate, queryBatchProductSkcMatted } from '@api/box/boxLook'
import { querySysCateTree } from '@api/box/api'

const columns = [
  {
    title: '序号',
    width: 60,
    customRender: (text, record, index) => `${index + 1}`
  },
  {
    title: '商品',
    width: 250,
    scopedSlots: { customRender: 'product' }
  },
  {
    title: '操作',
    align: 'right',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  components: {
    Product,
    JImageUpload,
    KonvaImg
  },
  data() {
    return {
      createImgFlag: false,
      konvaImgVisible: false,
      createStylingList: [],
      visible: false,
      spinning: false,
      productList: [],
      columns,
      selectedRowKeys: [],
      imgList: [],
      videoList: [],
      form: {
        labelList: [],
        imgList: [],
        videoList: []
      },
      rules: {
        fashionerId: [{ required: true, message: '请选择', trigger: 'change' }],
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        multip: [{ required: true, message: '请选择', trigger: 'blur' }],
        imgList: [{ required: false, message: '请上传', trigger: ['blur', 'change'] }],
        videoList: [{ required: false, message: '请上传', trigger: ['blur', 'change'] }]
      },
      yearShowOne: false,
      tags: []
    }
  },
  watch: {},
  created() {
    this.getSysCateTree()
    this.getDetails()
  },
  mounted() {
    console.log('1111')
  },
  methods: {
    // 标签
    getSysCateTree() {
      querySysCateTree('B08')
        .then(res => {
          const { code, result, message } = res
          console.log(res, 'data')
          if (code == 0) {
            this.tags = result
          } else {
            this.$message.error(message)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    handleDeleteProduct(index) {
      this.productList.splice(index, 1)
    },

    handleAddProduct(v) {
      let ids = this.productList.map(e => e.id + e.colorno)
      if (ids.includes(v.id + v.colorno)) {
        this.$message.error('不可重复添加相同的商品！')
        return
      }
      this.productList.push(v)
    },

    onSelectChange(selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
    },

    handleTagChange(tag, checked) {
      console.log(checked, tag)
      const { labelList } = this.form
      const nextSelectedTags = checked ? [...labelList, tag] : labelList.filter(t => t !== tag)
      this.form.labelList = nextSelectedTags
    },

    handleSubmit() {
      this.$refs.rulesForm.validate(valid => {
        if (valid) {
          const match = JSON.parse(this.$route.query.match)
          console.log(this.productList, 'this.productList')
          if (!this.productList.length) {
            this.$message.error('请添加商品！')
            return
          }
          const data = {
            requestData: {
              look: {
                source: match.source,
                imgList: this.form.imgList.map(e => {
                  return {
                    type: 0,
                    url: e.url
                  }
                }),
                labelList: this.form.labelList,
                lookDiagram: '',
                productList: this.productList.map(e => {
                  return {
                    productBrand: e.brand,
                    productCode: e.name,
                    productName: e.value,
                    productColorName: e.color_name,
                    productColor: e.colorno,
                    productId: e.id,
                    productImage: e.imgurl
                  }
                }),
                videoList: this.form.videoList.map(e => {
                  return {
                    type: 1,
                    url: e.url
                  }
                })
              },
              match: {
                ...match,
                // season: match.season.join(','),
                lookGender: match.lookGender.join(',')
              }
            }
          }
          console.log(JSON.stringify(data), 'data')
          matchCreate(data)
            .then(res => {
              this.spinning = false
              if (res.code === 0) {
                this.$message.success('保存成功！')
                this.$router.push(`/box/boxLook/index`)
              } else {
                this.$message.error(res.msg)
              }
            })
            .catch(err => {
              this.spinning = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    handleBack() {
      this.$router.go(-1)
    },

    // 上传图片
    getUploadParams() {
      return { ...globalData.uploadParams }
    },
    fileImageChange(list) {
      console.log('list', list)
      this.form.imgList = list
    },
    fileVideoChange(list) {
      this.form.videoList = list
    },

    handleCreateImg() {
      if (this.selectedRowKeys.length < 1) {
        this.$message.error('至少选一件！')
        return
      }
      if (this.selectedRowKeys.length > 3) {
        this.$message.error('最多只能选择三件！')
        return
      }
      const productList = this.selectedRowKeys.map(e => JSON.parse(e))
      console.log(productList, 'productListproductList')
      const productColors = productList.map(item => {
        return {
          colorNo: item.colorno,
          productId: item.id
        }
      })
      const data = {
        requestData: {
          productColors: productColors
        }
      }
      this.createImgFlag = true
      queryBatchProductSkcMatted(data)
        .then(res => {
          console.log(res.data, 'data')
          if (res.code == 0) {
            const list = res.data
            this.createStylingList = list
            this.createImgFlag = false
            this.konvaImgVisible = true
          } else {
            this.createImgFlag = false
            this.$message.error(res.data.msg)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    getDetails() {
      const { id, extendJson, lookLabelList, productList } = JSON.parse(this.$route.query.match)
      if (!id) return
      this.spinning = true
      console.log(JSON.parse(extendJson), 'JSON.parse(extendJson)')
      const { imgList, videoList } = JSON.parse(extendJson)
      this.imgList = imgList || []
      this.productList = productList.map(e => {
        return {
          brand: e.productBrand,
          name: e.productCode,
          value: e.productName,
          color_name: e.productColorName,
          colorno: e.productColor,
          id: e.productId,
          imgurl: e.productImage
        }
      })
      this.videoList = videoList || []
      this.form.labelList = lookLabelList
      this.spinning = false
    }
  }
}
</script>
<style lang="less" scoped>
/deep/.ant-tag {
  cursor: pointer;
}
/deep/.size-box {
  display: none;
}
/deep/.ant-pro-pages-list-projects-cardList .cardItemContent {
  padding: 0px 0px 20px;
}
/deep/.ant-pro-pages-list-projects-cardList .cardItemContent .price {
  display: none;
}
/deep/.ant-pro-pages-list-projects-cardList .cardItemContent .blue {
  display: none;
}
/deep/ .ant-pro-pages-list-projects-cardList .ant-card-body {
  min-height: 0;
}
.product-wrapper {
  display: flex;
  .img {
    display: block;
    width: 60px;
    height: 60px;
    border: 1px dashed #f5f5f5;
    object-fit: scale-down;
  }
  .text {
    flex: 1;
    margin-left: 10px;
    line-height: 20px;
    font-size: 12px;
    color: #333;
    .t {
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 1;
      word-break: break-all; /* 追加这一行代码 */
      /* autoprefixer: off */
      -webkit-box-orient: vertical;
      /* autoprefixer: on */
    }
  }
}
.icon-img {
  width: 86px;
  height: 86px;
  object-fit: scale-down;
}
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
